package com.infolab.aims.web.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.DefaultSavedRequest;

import com.infolab.aims.GlobalConstant;
import com.infolab.aims.common.bean.SearchCriteria;
import com.infolab.aims.domain.SystemUser;
import com.infolab.aims.service.intf.SystemUserService;


public class AuthenticationHandler implements AuthenticationSuccessHandler{

	Log logger = LogFactory.getLog(getClass());
	
	@Autowired
	SystemUserService systemUserService;
	
	public void onAuthenticationSuccess(HttpServletRequest request,
			HttpServletResponse response, Authentication authentication)
			throws IOException, ServletException {
		
		SearchCriteria searchCriteria = new SearchCriteria();
		User principal = (User) authentication.getPrincipal();
		searchCriteria.addSearchCriteria("userName", principal.getUsername());
		SystemUser systemUser = systemUserService.findUser(searchCriteria);
		request.getSession().setAttribute(GlobalConstant.SESSION_CURRENT_SYSTEMUSER, systemUser);
		
		logger.info("Successfully login "+principal.getUsername());
		
		DefaultSavedRequest defaultSavedRequest = (DefaultSavedRequest) request.getSession().getAttribute(WebAttributes.SAVED_REQUEST);
		
		if(defaultSavedRequest!=null){
			String url = defaultSavedRequest.getRedirectUrl();
			if(StringUtils.lastIndexOf(url, "/") > -1){
				response.sendRedirect(request.getContextPath() + "/indexView");
			}else{
				response.sendRedirect(defaultSavedRequest.getRedirectUrl());
			}
		}
		else
			response.sendRedirect(request.getContextPath() + "/indexView");

	}

}
